package com.jcp.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;
import com.jcp.util.GsonUtils;
import com.jcp.util.HttpUtil;

/*
 * 车牌识别类
 * author:戴布斯
 */
public class Sample {

	// 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取
	public static String accessToken = "24.748650ffa8865d8ac541dbcdb880776d.2592000.1575077471.282335-17655707";

	// 用来获取权限token,返回值类型String
	public static String getAuth() {
		// 车牌识别接口的 API Key
		String clientId = "lS23630TBpVcoxYdo3NC6yGR";// 戴布斯的API Key
		// 车牌识别接口的Secret Key
		String clientSecret = "NahgMFMAHWR2UhZlc82OMLFAmFvyA0kN";// 戴布斯的Secret Key
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 车牌识别接口的 API Key
				+ "&client_id=" + clientId
				// 3. 车牌识别接口的Secret Key
				+ "&client_secret=" + clientSecret;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			// 控制台输出返回结果
			System.err.println("result:" + result);

			// 解析json，得到access_token
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");

			return access_token;// 返回值
		} catch (Exception e) {
			System.err.printf("获取token失败！");
			e.printStackTrace(System.err);
		}
		return null;
	}

	public void sample3() {
		String image = "C:\\Users\\戴布斯\\Desktop\\cp.jpg";
		sample2(image);
	}

	public static void sample2(String url) {
		// 设置APPID/AK/SK
		String APP_ID = "17655707";
		String API_KEY = "lS23630TBpVcoxYdo3NC6yGR";
		String SECRET_KEY = "NahgMFMAHWR2UhZlc82OMLFAmFvyA0kN";
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
		// 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("multi_detect", "true");

		// 参数为本地路径
		// JSONObject res = client.plateLicense(image, options);
		// System.out.println(res.toString(2));

		// 通用文字识别, 图片参数为远程url图片
		JSONObject res = client.basicGeneralUrl(url, options);
		System.out.println(res.toString(2));

		// 参数为二进制数组
		// byte[] file = readFile("test.jpg");
		// res = client.plateLicense(file, options);
		// System.out.println(res.toString(2));

		// 对json的解析
		JSONArray res2 = res.getJSONArray("words_result");
		System.out.println("这是words_result:" + res2);
		JSONObject res3 = res2.getJSONObject(0);
		System.out.println("res3:" + res3);
		String res4 = res3.getString("number");
		System.out.println("车牌:" + res4);
	}

	public static String scan(String base) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
		try {

			// 读取本地图片输入流
			/*
			 * FileInputStream inputStream = new FileInputStream("F:/ch1.png"); String base
			 * = Base64.encodeBase64String(IOUtils.toByteArray(inputStream));
			 * logger.info(base);
			 */
			String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(base, "UTF-8");

			/*
			 * Map<String, Object> map = new HashMap<>(); map.put("image", base);
			 * map.put("image_type", "BASE64");
			 * 
			 * String param = GsonUtils.toJson(map);
			 */

			String result = HttpUtil.post(url, accessToken, params);
			System.out.println(result);

			JSONObject json = new JSONObject(result);

			// 对json的解析
			JSONArray res2 = json.getJSONArray("words_result");
			System.out.println("这是words_result:" + res2);
			JSONObject res3 = res2.getJSONObject(0);
			System.out.println("res3:" + res3);
			String res4 = res3.getString("words");
			System.out.println("车牌:" + res4);
			return res4;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
